package com.jdy.haoduoaiteacher.util;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import com.jdy.haoduoaiteacher.MyTeacherApp;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class VoiceRecorder {

  private MediaRecorder mRecorder;

  static final String PREFIX = "voice_";

  private static final String RECORD_PREFIX = "record_";

  // static final String EXTENSION = ".mp4";
  static final String EXTENSION = ".mp3";

  private boolean isRecording = false;

  private long mStartTime;

  private String mVoiceFilePath;

  private String mVoiceFileName;

  private File mFile;

  private final Handler mHandler;

  private Timer mTimer;

  private TimerTask timerTask;

  private final int START_IMAGE_INDEX = 0;

  private final int END_IMAGE_INDEX = 5;

  private int mCurrentImageIndex = START_IMAGE_INDEX;

  private MediaPlayer mPlayer;

  public VoiceRecorder(Handler micImageHandler) {
    // TODO Auto-generated constructor stub
    this.mHandler = micImageHandler;
    FileUtils.CreateFolder("haoduoaiteacher");
  }

  public void startTimer() {
    // set a new Timer
    mTimer = new Timer();

    // initialize the TimerTask's job
    initializeTimerTask();

    // schedule the timer, after the first 5000ms the TimerTask will run every
    // 10000ms
    mTimer.schedule(timerTask, 0, 200); //
  }

  private void startPlaying() {
    mPlayer = new MediaPlayer();
    try {
      mPlayer.setDataSource(mVoiceFileName);
      mPlayer.prepare();
      mPlayer.start();
    } catch (IOException e) {
      LeXiaoXiaoBanLog.e("VoiceRecorder", "prepare() failed");
    }
  }

  /**
   * Get duration of current voice file.
   * 
   * @param context
   * @return
   */
  public int getDuration(Context context) {
    MediaPlayer mp = MediaPlayer.create(context, Uri.parse(mVoiceFileName));
    return mp.getDuration() / 1000;
  }

  public void stopTimer() {
    // stop the timer, if it's not already null
    if (mTimer != null) {
      mTimer.cancel();
      mTimer = null;
    }
  }

  public void initializeTimerTask() {
    timerTask = new TimerTask() {
      @Override
      public void run() {
         Message msg = new Message();
         if (mCurrentImageIndex > END_IMAGE_INDEX)
         mCurrentImageIndex = START_IMAGE_INDEX;
         msg.what = mCurrentImageIndex;
         mHandler.sendMessage(msg);
         mCurrentImageIndex++;
      }
    };
  }

  public String getVoiceFilePath() {
    return mVoiceFilePath;
  }

  public int stopRecoding() {
    if (isRecording) {
      isRecording = false;
      stopTimer();
      if (mRecorder != null) {
        mRecorder.setOnErrorListener(null);
        try {
          mRecorder.stop();
        } catch (IllegalStateException e) {
          // TODO
        } finally {
          mRecorder.reset();
          mRecorder.release();
          mRecorder = null;
        }
      }
      File file = new File(mVoiceFileName);
      int fileSize = Integer.parseInt(String.valueOf(file.length() / 1024));
      return fileSize;
    } else {
      return 0;
    }
  }

  // Stop and delete the file.
  public void discardRecording() {

    stopRecoding();
    File recordedFile = new File(this.mVoiceFileName);
    recordedFile.delete();
  }

  public boolean isRecording() {

    return isRecording;
  }

  public void startRecording(Object object, String toChatUsername,
      Context applicationContext) {

    isRecording = true;
    startTimer();

    if (mRecorder != null) {
      mRecorder.stop();
      mRecorder.release();
      mRecorder = null;
    }

    try {
      this.mRecorder = new MediaRecorder();
      this.mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
      this.mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
      this.mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
      this.mVoiceFileName = Environment.getExternalStorageDirectory()
          .getAbsolutePath();
      // file name must be correct to avoid 'invalid state 4!'

   this.mVoiceFileName += "/" + MyTeacherApp.getAppContext().getPackageName();

      File foder = new File(this.mVoiceFileName);
      if (!foder.exists()) {
        foder.mkdirs();
      }

      this.mVoiceFileName += "/" + PREFIX + ".mp4";
      this.mRecorder.setOutputFile(mVoiceFileName);
      LeXiaoXiaoBanLog.e("mVoiceFileName", mVoiceFileName);
      mRecorder.prepare();
    } catch (IOException e) {
      LeXiaoXiaoBanLog.e("VoiceRecorder", "prepare() failed");
    }

    mRecorder.start();
  }

  public void startRecording(String name) {

    isRecording = true;
    try {
      this.mRecorder = new MediaRecorder();
      this.mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
      this.mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
      this.mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);

      // mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
      // mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
      // mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);

      this.mVoiceFileName = Environment.getExternalStorageDirectory()
          .getAbsolutePath();
      // file name must be correct to avoid 'invalid state 4!'
      // this.mVoiceFileName += "/lexiaobao/" + name + new
      // SimpleDateFormat("yyyyMMddhhmmss'.3gp'").format(new Date());
      // this.mVoiceFileName += "/lexiaobao/"/* + name +"_" */
      // + System.currentTimeMillis() + EXTENSION;
      this.mVoiceFileName += "/haoduoaiteacher/"/* + name +"_" */
          + RECORD_PREFIX + name + EXTENSION;
      this.mRecorder.setOutputFile(mVoiceFileName);
      LeXiaoXiaoBanLog.e("mVoiceFileName", mVoiceFileName);
      mRecorder.prepare();
    } catch (IOException e) {
      LeXiaoXiaoBanLog.e("VoiceRecorder", "prepare() failed");
    }

    mRecorder.start();
  }

  public String getVoiceFileName() {

    return mVoiceFileName;
  }

}
